<template>
	<view class="container">
		<!-- 时间查询条件 -->
		<view class="time-filter">
			<!-- <view class="filter-item" @click="showTimePopup = true">
				<view class="filter-text">{{selectedTimeText}}</view>
				<u-icon name="arrow-down" size="24" color="#666"></u-icon>
			</view> -->
			<view class="filter-item" @click="showMonthPopup = true">
				<view class="filter-text">{{selectedMonthText}}</view>
				<u-icon name="arrow-down" size="24" color="#666"></u-icon>
			</view>
			<!-- 添加工资计算按钮 - 只有超级管理员可见 -->
			<view class="payment-btn" @click="payroll()" v-if="isSuperAdmin">
				工资计算
			</view>
		</view>
		<!-- 饼状图 -->
		<view class="chart-container">
			<pie-chart :data="pieChartData" />
		</view>
		<!-- 列表区域 -->
		<view class="wrap">
			<!-- <view class="search">
				<u-search v-model="keywords" @custom="search" @search="search"></u-search>
			</view> -->
			<view class="chart-header-bar">
				<view class="chart-header-title">图表详细</view>
				<view class="chart-header-sort" @click="toggleOrderBy">排序</view>
			</view>
			<view class="list-container">
				<u-cell-group class="list" :border="false">
					<view class="list-item" :options="options" v-for="(item, index) in list" :key="item.id" :index="index" @click="optionsClick">
						<u-cell-item :arrow="true" @click="navToDetails(item)">
							<view slot="title" class="title-container">
								<view class="office-name">{{item.createByName}}</view>
								<view class="status-normal" :style="{ color: getStatusColor(item.status) }">{{getStatusText(item.status)}}</view>
							</view>
							<text slot="label">
								<view class="label-row">
									<text class="label-text">月份：{{item.salaryDate}}</text>
									<text class="label-text">实发工资：<text :class="{
										'red-text': parseFloat(item.actualSalary) < 0,
										'blue-text': parseFloat(item.actualSalary) >= 0 && parseFloat(item.actualSalary) <= 10000,
										'purple-text': parseFloat(item.actualSalary) > 10000
									}">{{formatNumber(item.actualSalary)}}</text></text>
								</view>
								<view class="label-row">
									<text class="label-text">本店店铺：{{item.officeName}}</text>
									<text class="label-text">基本工资：{{formatNumber(item.baseSalary)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">实际总销量：{{formatNumber(item.totalQuantity)}}</text>
									<text class="label-text">销量提成：{{formatNumber(item.commission)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">超额奖励：{{formatNumber(item.excessReward)}}</text>
									<text class="label-text">任务奖金：{{formatNumber(item.taskReward)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">超勤奖励：{{formatNumber(item.fullAttendanceReward)}}</text>
									<text class="label-text">房补费用：{{formatNumber(item.housingSubsidyFee)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">帮出票总量：{{formatNumber(item.bfdTotalQuantity)}}</text>
									<text class="label-text">出票奖金：{{formatNumber(item.ticketIssuanceReward)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">分红费用：{{formatNumber(item.dividendSetting)}}</text>
									<text class="label-text">请假天数：{{item.leaveDays}}</text>
									
								</view>
								<view class="label-row">
									<text class="label-text">违规罚款：{{formatNumber(item.violationFines)}}</text>
									<text class="label-text">宿舍费用：{{formatNumber(item.dormitoryFees)}}</text>
								</view>
								<view class="label-row">
									<text class="label-text">休息差价：{{formatNumber(item.restPriceDifference)}}</text>
									<text class="label-text">其他说明：{{item.extendParam}}</text>
								</view>
							</text>
						</u-cell-item>
					</view>
				</u-cell-group>
			</view>
			
			<!-- 合计区域 -->
			<view class="total-bar" @click="showTotalDetail" v-if="list && list.length > 0">
				<view class="total-item">
					<text>总工资：</text>
					<text class="value">¥{{totalAmount}}</text>
				</view>
				<view class="total-item">
					<text>人数：</text>
					<text class="value">{{totalCount}}</text>
				</view>
			</view>
		</view>
		<!-- 合计详情弹窗 -->
		<u-popup v-model="showDetail" mode="bottom" border-radius="20" v-if="list && list.length > 0">
			<view class="total-detail">
				<view class="detail-header">
					<text class="title">合计数据</text>
					<view class="close-btn" @click="showDetail = false">×</view>
				</view>
				<view class="detail-content">
					<view class="detail-item">
						<text>总工资：</text>
						<text class="value">¥{{totalAmount}}</text>
					</view>
					<view class="detail-item">
						<text>人数：</text>
						<text class="value">{{totalCount}}</text>
					</view>
					<view class="detail-item">
						<text class="label">实际总销量：</text>
						<text class="value">¥{{totalQuantity}}</text>
					</view>
					<view class="detail-item">
						<text class="label">销量提成：</text>
						<text class="value">¥{{totaltcommission}}</text>
					</view>
					<view class="detail-item">
						<text class="label">超额奖金：</text>
						<text class="value">¥{{totalexcessReward}}</text>
					</view>
					<view class="detail-item">
						<text class="label">任务奖金：</text>
						<text class="value">¥{{totaltaskReward}}</text>
					</view>
					<view class="detail-item">
						<text class="label">房补费用：</text>
						<text class="value">¥{{totalhousingSubsidyFee}}</text>
					</view>
					<view class="detail-item">
						<text class="label">帮出票总量：</text>
						<text class="value">¥{{totalbfdTotalQuantity}}</text>
					</view>
					<view class="detail-item">
						<text class="label">出票奖金：</text>
						<text class="value">¥{{totalticketIssuanceReward}}</text>
					</view>
					<view class="detail-item">
						<text class="label">分红费用：</text>
						<text class="value">¥{{totaldividendSetting}}</text>
					</view>
					<view class="detail-item">
						<text class="label">请假天数：</text>
						<text class="value">¥{{totalleaveDays}}</text>
					</view>
					<view class="detail-item">
						<text class="label">违规罚款：</text>
						<text class="value">¥{{totalviolationFines}}</text>
					</view>
					<view class="detail-item">
						<text class="label">宿舍费用：</text>
						<text class="value">¥{{totaldormitoryFees}}</text>
					</view>
					<view class="detail-item">
						<text class="label">休息差价：</text>
						<text class="value">¥{{totalrestPriceDifference}}</text>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 时间选择弹窗 -->
		<u-popup v-model="showTimePopup" mode="bottom" border-radius="0">
			<view class="time-popup">
				<view class="popup-header">
					<view class="title">请选择时间范围</view>
				</view>
				<view class="popup-content">
					<view class="time-option" 
						v-for="(item, index) in timeOptions" 
						:key="index"
						@click="selectTimeOption(item)">
						<view class="option-text">{{item.label}}</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 自定义时间选择弹窗 -->
		<u-popup v-model="showCustomDatePopup" mode="bottom" border-radius="0">
			<view class="date-picker-popup">
				<view class="date-header">请选择时间范围</view>
				<view class="date-display">{{tempStartDate}}~{{tempEndDate}}</view>
				<view class="date-tabs">
					<view class="tab-item" :class="{'active': isSelectingStart}" @click="switchToStart">
						<text>{{tempStartDate}} 开始</text>
					</view>
					<view class="tab-item" :class="{'active': !isSelectingStart}" @click="switchToEnd">
						<text>{{tempEndDate}} 结束</text>
					</view>
				</view>
				<view class="picker-labels">
					<text class="label-item">年</text>
					<text class="label-item">月</text>
					<text class="label-item">日</text>
				</view>
				<view class="picker-container">
					<picker-view class="picker-view" :indicator-style="indicatorStyle" :value="pickerValue" @change="onPickerChange">
						<picker-view-column>
							<view class="picker-item" v-for="year in years" :key="year">{{year}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="month in months" :key="month">{{month.padStart(2, '0')}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="picker-item" v-for="day in days" :key="day">{{day.padStart(2, '0')}}</view>
						</picker-view-column>
					</picker-view>
				</view>
				<view class="picker-actions">
					<view class="picker-btn cancel" @click="cancelDatePicker">取消</view>
					<view class="picker-btn confirm" @click="confirmDatePicker">完成</view>
				</view>
			</view>
		</u-popup>
		<!-- 月份选择弹窗 -->
		<u-popup v-model="showMonthPopup" mode="bottom" border-radius="0">
			<view class="time-popup">
				<view class="popup-header">
					<view class="title">请选择月份</view>
				</view>
				<scroll-view class="popup-content" scroll-y="true">
					<view class="time-option" 
						v-for="(item, index) in monthOptions" 
						:key="index"
						@click="selectMonthOption(item)">
						<view class="option-text">{{item.name}}</view>
					</view>
				</scroll-view>
			</view>
		</u-popup>
	</view>
</template>

<script>
/**
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 */
import PieChart from '@/components/uni-data-charts/qiun-data-charts.vue'

export default {
	components: {
		PieChart
	},
	data() {
		return {
			type:1,
			keywords: '',
			query: {
				pageNo: 1,
				pageSize: 2000,
				calculateMonth:'',
				month:'',
				createByName:'',
				officeCode:'',
				orderBy:'a.actual_salary desc',
				status:'',
			},
			list: [],
			count: 0,
			loadStatus: 'loadmore',
			options: [
				// {text: '删除', style: { background: '#dd524d'}},
				// {text: '上传', style: { background: '#414ee0'}},
			],
			mainTypeList:[],
			// 饼图数据
			pieChartData: [],
			showDetail: false, // 控制合计详情弹窗
			totalAmount: '0.00', // 工资
			totalCount: '0', // 人数
			totalQuantity: '0.00', // 实际总销量
			totaltcommission: '0.00', // 销量提成
			totalexcessReward: '0.00', // 超额奖金
			totaltaskReward: '0.00', // 任务奖金
			totalhousingSubsidyFee: '0.00', // 房补费用
			totalbfdTotalQuantity: '0.00', // 帮出票总量
			totalticketIssuanceReward: '0.00', // 出票奖金
			totaldividendSetting: '0.00', // 分红费用
			totalleaveDays: '0', // 请假天数
			totalviolationFines: '0.00', // 违规罚款
			totaldormitoryFees: '0.00', // 宿舍费用
			totalrestPriceDifference: '0.00', // 休息差价
			// 时间筛选相关
			showTimePopup: false,
			showCustomDatePopup: false,
			selectedTimeOption: 'January',
			timeOptions: [
				// { label: '全部', value: 'all' },
				// { label: '今日', value: 'today' },
				// { label: '昨日', value: 'yesterday' },
				// { label: '本月', value: 'month' },
				// { label: '上个月', value: 'lastMonth' },
				// { label: '其它时间', value: 'custom' }
				{ label: '1月份', value: 'January' },
				{ label: '2月份', value: 'February' },
				{ label: '3月份', value: 'March' },
				{ label: '4月份', value: 'April' },
				{ label: '5月份', value: 'May' },
				{ label: '6月份', value: 'June' },
				{ label: '7月份', value: 'July' },
				{ label: '8月份', value: 'August' },
				{ label: '9月份', value: 'September' },
				{ label: '10月份', value: 'October' },
				{ label: '11月份', value: 'November' },
				{ label: '12月份', value: 'December' },
			],
			startDate: '',
			endDate: '',
			minDate: '2020-01-01',
			maxDate: new Date().toISOString().split('T')[0],
			// 时间选择器相关
			pickerValue: [2, 3, 1], // 默认选中值
			years: [], // 年份选项
			months: [], // 月份选项
			days: [], // 日期选项
			tempStartDate: '', // 临时开始日期
			tempEndDate: '', // 临时结束日期
			isSelectingStart: true, // 是否正在选择开始日期
			indicatorStyle: 'height: 80rpx; border-top: 1px solid #e5e5e5; border-bottom: 1px solid #e5e5e5;',
			// 月份相关
			showMonthPopup: false,
			selectedMonth: '',
			monthOptions: [],
		};
	},
	computed: {
		selectedTimeText() {
			const option = this.timeOptions.find(item => item.value === this.selectedTimeOption);
			if (this.selectedTimeOption === 'custom' && this.startDate && this.endDate) {
				return `${this.startDate} 至 ${this.endDate}`;
			}
			return option ? option.label : '本月';
		},
		selectedMonthText() {
			if (this.selectedMonth) {
				const option = this.monthOptions.find(item => item.value === this.selectedMonth);
				return option ? option.name : '本月';
			}
			return '本月';
		},
		// 判断是否为超级管理员
		isSuperAdmin() {
			const user = this.vuex_user;
			if (!user) return false;
			
			// 检查用户名是否为超级管理员
			const superAdminUsers = ['system', 'admin', 'superadmin'];
			if (user.loginCode && superAdminUsers.includes(user.loginCode.toLowerCase())) {
				return true;
			}
			
			// 检查用户类型是否为管理员
			if (user.userType === 'admin' || user.userType === 'superadmin') {
				return true;
			}
			
			// 检查是否有管理员角色标识
			if (user.isAdmin === true || user.isSuperAdmin === true) {
				return true;
			}
			
			return false;
		}
	},
	onLoad(params) {
		// 设置页面标题
		let title = '工资表'
		uni.setNavigationBarTitle({
			title: title
		});
		// 设置默认时间范围
		// this.setDefaultTimeRange();
		// 初始化图表数据
		this.initChartData();
		// 加载月份字典数据
		this.loadMonthData();
		// 主类型
		// this.$u.api.mainType.treeData({dictType:'sale_main_type'}).then(res => {
		// 	this.mainTypeList = res;
		// });
		setTimeout(() => {
			this.loadList();
		}, 100);
	},
	onShow() {
		if (uni.getStorageSync('refreshList') === true){
			uni.removeStorageSync('refreshList');
			this.search('');
		}
	},
	methods: {
		getStatusText(status) {
			if (status.indexOf('0') != -1) return '正常';
			if (status.indexOf('1') != -1) return '删除';
			if (status.indexOf('2') != -1) return '停用';
			if (status.indexOf('3') != -1) return '冻结待交款';
			if (status.indexOf('4') != -1) return '待审';
			if (status.indexOf('5') != -1) return '驳回';
			if (status.indexOf('9') != -1) return '完结';
			return '';
		},
		getStatusColor(status) {
			if (status.indexOf('0') != -1) return '#4CAF50';  // 正常 - 绿色
			if (status.indexOf('1') != -1) return '#FF9800';  // 删除 - 橙色
			if (status.indexOf('2') != -1) return '#F44336';  // 停用 - 红色
			if (status.indexOf('3') != -1) return '#FFC107';  // 冻结待交款 - 黄色
			if (status.indexOf('4') != -1) return '#2196F3';  // 待审 - 蓝色
			if (status.indexOf('5') != -1) return '#9C27B0';  // 驳回 - 紫色
			if (status.indexOf('9') != -1) return '#666666';  // 完结 - 灰色
			return '#666666'; // 默认颜色
		},
		findNameByValue(array, value) {
		    const foundObject = array.find(item => item.dictValue == value);
		    return foundObject ? foundObject.dictLabel : null;
		},
		// 加载月份字典数据
		loadMonthData() {
			this.$u.api.dictData({dictType: 'month_code'}).then(res => {
				if (typeof res === 'object' && res.result === 'login'){
					return;
				}
				// 添加"本月"选项
				this.monthOptions = [
					{ value: '', name: '本月' },
					...res
				];
			});
		},
		// 选择月份
		selectMonthOption(item) {
			this.selectedMonth = item.value;
			this.query.month = item.value;
			this.showMonthPopup = false;
			this.loadList();
		},
		loadMore() {
			this.loadStatus = "loading";
			setTimeout(() => {
				this.query.pageNo += 1;
				this.loadList();
			}, 100);
		},
		loadList() {
			let that = this
			// 添加时间范围到查询条件
			if(this.query.pageNo == 1){
				this.list = [];
				// 清空列表时同时更新饼图数据
				this.initChartData();
			}
			
			this.$u.api.payroll.list(this.query).then(res => {
				if (!res.list || res.list.length == 0){
					this.loadStatus = "nomore";
					// 确保没有数据时更新饼图
					this.initChartData();
					return;
				}
				
				// 转换为数组
				this.list = res.list;
				
				this.count = this.list.length;
				this.query.pageNo = res.pageNo;
				this.query.pageSize = res.pageSize;
				this.loadStatus = "loadmore";
				
				// 更新图表数据
				this.initChartData();
				
				// 计算合计数据
				this.calculateTotal();
			});
		},
		optionsClick(rowIndex, btnIndex) {
			let self = this, row = self.list[rowIndex];
			if(btnIndex == 1) {
				this.navTo('formUpload?id='+row.id);
			} else if(btnIndex == 0) {
				uni.showModal({
					title: '提示',
					content: '确认要删除该数据吗？',
					showCancel: true,
					success: function (res2) {
						if (res2.confirm) {
							self.$u.api.salesManagement.delete({id: row.id}).then(res => {
								self.$u.toast(res.message);
								if (res.result == 'true'){
									self.list.splice(rowIndex, 1);
								}
							});
						}
					}
				});
			}
		},
		search(value) {
			this.list = [];
			this.query.pageNo = 0;
			// this.query.testInput = value;
			this.loadList();
		},
		navTo(url) {
			uni.navigateTo({
				url: url
			});
		},
		navToDetails(item) {
			// 使用全局数据存储传递数据，避免URL编码问题
			uni.setStorageSync('payrollDetailData', item);
			this.navTo('payrollDetails?type=' + this.type);
		},
		initChartData() {
			// 如果没有数据，显示无数据提示
			if (!this.list || this.list.length === 0) {
				this.pieChartData = [{
					name: '暂无数据',
					value: 100,
					color: '#e0e0e0'
				}];
				return;
			}
			
			// 将列表数据转换为饼图所需的数据格式
			let chartData = this.list.map(item => ({
				name: item.createByName,
				value: parseFloat(item.actualSalary) || 0
			}));
			
			// 如果数据条数大于5，进行特殊处理
			if (chartData.length > 5) {
				// 按value值从大到小排序
				chartData.sort((a, b) => b.value - a.value);
				
				// 获取前5条数据
				let top5Data = chartData.slice(0, 5);
				
				// 计算剩余数据的value总和
				let otherValue = chartData.slice(5).reduce((sum, item) => sum + item.value, 0);
				
				// 如果有剩余数据，添加"其他"项
				if (otherValue > 0) {
					top5Data.push({
						name: '其他',
						value: otherValue
					});
				}
				
				this.pieChartData = top5Data;
			} else {
				this.pieChartData = chartData;
			}
		},
		showTotalDetail() {
			this.showDetail = true;
		},
		// 计算合计数据
		calculateTotal() {
			if (this.list && this.list.length > 0) {
				// 计算总工资
				this.totalAmount = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.actualSalary) || 0);
				}, 0).toFixed(2);
				
				// 人数
				this.totalCount = this.list.length.toString();
				
				// 计算实际总销量
				this.totalQuantity = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.totalQuantity) || 0);
				}, 0).toFixed(2);
				
				// 计算销量提成
				this.totaltcommission = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.commission) || 0);
				}, 0).toFixed(2);
				
				
				// 计算超额奖金
				this.totalexcessReward = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.excessReward) || 0);
				}, 0).toFixed(2);

				// 计算任务奖金
				this.totaltaskReward = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.taskReward) || 0);
				}, 0).toFixed(2);

				// 计算房补费用
				this.totalhousingSubsidyFee = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.housingSubsidyFee) || 0);
				}, 0).toFixed(2);

				// 计算帮出票总量
				this.totalbfdTotalQuantity = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.bfdTotalQuantity) || 0);
				}, 0).toFixed(2);

				// 计算出票奖金
				this.totalticketIssuanceReward = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.ticketIssuanceReward) || 0);
				}, 0).toFixed(2);

				// 计算分红费用
				this.totaldividendSetting = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.dividendSetting) || 0);
				}, 0).toFixed(2);

				// 计算请假天数
				this.totalleaveDays = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.leaveDays) || 0);
				}, 0);

				// 计算违规罚款
				this.totalviolationFines = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.violationFines) || 0);
				}, 0).toFixed(2);

				// 计算宿舍费用
				this.totaldormitoryFees = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.dormitoryFees) || 0);
				}, 0).toFixed(2);

				// 计算休息差价
				this.totalrestPriceDifference = this.list.reduce((sum, item) => {
					return sum + (parseFloat(item.restPriceDifference) || 0);
				}, 0).toFixed(2);
				
			}
		},
		setDefaultTimeRange() {
			const now = new Date();
			const year = now.getFullYear();
			const month = now.getMonth();
			const date = now.getDate();
			
			switch (this.selectedTimeOption) {
				case 'all':
					// 全部时间，设置为最早时间到当前时间
					this.startDate = this.minDate;
					this.endDate = this.maxDate;
					break;
				case 'today':
					// 今天
					this.startDate = this.formatDate(now);
					this.endDate = this.formatDate(now);
					break;
				case 'yesterday':
					// 昨天
					const yesterday = new Date(now);
					yesterday.setDate(date - 1);
					this.startDate = this.formatDate(yesterday);
					this.endDate = this.formatDate(yesterday);
					break;
				case 'month':
					// 本月
					this.startDate = `${year}-${String(month + 1).padStart(2, '0')}-01`;
					this.endDate = this.formatDate(now);
					break;
				case 'lastMonth':
					// 上个月
					const lastMonth = new Date(year, month - 1, 1);
					this.startDate = `${year}-${String(month).padStart(2, '0')}-01`;
					// 获取上个月的最后一天
					const lastDayOfLastMonth = new Date(year, month, 0).getDate();
					this.endDate = `${year}-${String(month).padStart(2, '0')}-${lastDayOfLastMonth}`;
					break;
				case 'January':
					this.query.month = 1;
					break
				case 'February':
					this.query.month = 2;
					break
				case 'March':
					this.query.month = 3;
					break
				case 'April':
					this.query.month = 4;
					break
				case 'May':
					this.query.month = 5;
					break
				case 'June':
					this.query.month = 6;
					break
				case 'July':
					this.query.month = 7;
					break
				case 'August':
					this.query.month = 8;
					break
				case 'September':
					this.query.month = 9;
					break
				case 'October':
					this.query.month = 10;
					break
				case 'November':
					this.query.month = 11;
					break
				case 'December':
					this.query.month = 12;
					break
				
				case 'custom':
					// 自定义时间，保持原有值
					break;
			}
			
			// 更新查询条件
			this.query.startSaleDate = this.startDate;
			this.query.endSaleDate = this.endDate;
		},
		selectTimeOption(item) {
			this.selectedTimeOption = item.value;
			if (item.value === 'custom') {
				this.showTimePopup = false;
				this.isSelectingStart = true;
				// 初始化日期选择器
				this.initDatePicker();
				// 设置临时日期
				this.tempStartDate = this.startDate || this.formatDate(new Date());
				this.tempEndDate = this.endDate || this.formatDate(new Date());
				// 设置开始日期的picker值
				const startDate = new Date(this.tempStartDate);
				this.setPickerValue(startDate);
				this.showCustomDatePopup = true;
			} else {
				this.setDefaultTimeRange(item.value);
				this.showTimePopup = false;
				this.loadList();
			}
		},
		switchToStart() {
			this.isSelectingStart = true;
			// 设置当前选中的日期对应的 picker 值
			const startDate = this.tempStartDate ? new Date(this.tempStartDate) : new Date();
			this.setPickerValue(startDate);
			this.updateDays();
		},
		switchToEnd() {
			this.isSelectingStart = false;
			// 设置当前选中的日期对应的 picker 值
			const endDate = this.tempEndDate ? new Date(this.tempEndDate) : new Date();
			this.setPickerValue(endDate);
			this.updateDays();
		},
		setPickerValue(date) {
			const yearIndex = this.years.findIndex(year => year === date.getFullYear());
			const monthIndex = date.getMonth(); // 月份从0开始
			const dayIndex = date.getDate() - 1; // 日期从1开始
			this.pickerValue = [yearIndex, monthIndex, dayIndex];
		},
		initDatePicker() {
			// 生成年份选项（前5年到后5年）
			const currentYear = new Date().getFullYear();
			this.years = [];
			for (let i = currentYear - 5; i <= currentYear + 5; i++) {
				this.years.push(i);
			}
			
			// 生成月份选项 (1-12)
			this.months = Array.from({length: 12}, (_, i) => String(i + 1));
			
			// 生成日期选项
			this.updateDays();
			
			// 设置默认值为当前日期
			const now = new Date();
			this.setPickerValue(now);
		},
		updateDays() {
			const year = this.years[this.pickerValue[0]];
			const month = parseInt(this.months[this.pickerValue[1]]);
			const daysInMonth = new Date(year, month, 0).getDate();
			this.days = Array.from({length: daysInMonth}, (_, i) => String(i + 1));
		},
		onPickerChange(e) {
			this.pickerValue = e.detail.value;
			this.updateDays();
			
			const year = this.years[this.pickerValue[0]];
			const month = this.months[this.pickerValue[1]].padStart(2, '0');
			const day = this.days[this.pickerValue[2]].padStart(2, '0');
			const dateStr = `${year}-${month}-${day}`;
			
			if (this.isSelectingStart) {
				this.tempStartDate = dateStr;
			} else {
				this.tempEndDate = dateStr;
			}
		},
		cancelDatePicker() {
			this.showCustomDatePopup = false;
			// 重置临时日期
			this.tempStartDate = this.startDate;
			this.tempEndDate = this.endDate;
			this.isSelectingStart = true;
		},
		confirmDatePicker() {
			const startDate = new Date(this.tempStartDate);
			const endDate = new Date(this.tempEndDate);
			
			if (!this.isSelectingStart && endDate < startDate) {
				uni.showToast({
					title: '结束日期不能早于开始日期',
					icon: 'none'
				});
				return;
			}
			
			this.startDate = this.tempStartDate;
			this.endDate = this.tempEndDate;
			this.showCustomDatePopup = false;
			this.loadList();
		},
		formatDate(date) {
			const year = date.getFullYear();
			const month = String(date.getMonth() + 1).padStart(2, '0');
			const day = String(date.getDate()).padStart(2, '0');
			return `${year}-${month}-${day}`;
		},
		toggleOrderBy() {
			if (this.query.orderBy === 'a.actual_salary desc') {
				this.query.orderBy = 'a.actual_salary asc';
			} else {
				this.query.orderBy = 'a.actual_salary desc';
			}
			this.loadList();
		},
		formatNumber(value) {
			// Handle null, undefined, or empty string
			if (value === null || value === undefined || value === '') {
				return '0.00';
			}
			
			// Convert string to number if needed
			if (typeof value === 'string') {
				value = parseFloat(value);
			}
			
			// Check if it's a valid number
			if (isNaN(value)) {
				return '0.00';
			}
			
			// Format to 2 decimal places
			return value.toFixed(2);
		},
		payroll(){
			// 组织交款参数
			const paymentParams = {
				'month': this.query.month, 
			};
			
			// 这里添加交款逻辑
			uni.showModal({
				title: '工资计算',
				content: `计算生成 ${this.query.month} 月份工资？`,
				success: (res) => {
					if (res.confirm) {
						// 调用工资计算API
						this.$u.api.payroll.calculate(paymentParams).then(res => {
							if (res.result === 'true') {
								uni.showToast({
									title: res.message,
									icon: 'success'
								});
								// 刷新列表
								this.loadList();
							} else {
								uni.showToast({
									title: res.message || '生成失败',
									icon: 'none'
								});
							}
						}).catch(err => {
							uni.showToast({
								title: '生成失败，请重试',
								icon: 'none'
							});
						});
					}
				}
			});
		}
	}
};
</script>

<style lang="scss">
.container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	// padding: 20rpx;
	box-sizing: border-box;
}

.chart-container {
	width: 100%;
	background-color: #fff;
	max-height: 1200rpx;
	margin-top: 150rpx;
	margin-bottom: 50rpx;
}

page {
	background-color: #f8f8f8;
}
.btn-plus {
	position: absolute;
	bottom: 50rpx;
	right: 50rpx;
	z-index: 1;
	opacity: 0.6;
}
.btn-plus:hover {
	opacity: 1;
}

.list-container {
	padding-bottom: 100rpx;
}

.total-bar {
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	height: 88rpx;
	background-color: #ffffff;
	display: flex;
	align-items: center;
	justify-content: space-around;
	padding: 0 30rpx;
	box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
}

.total-item {
	display: flex;
	align-items: center;
	
	.value {
		color: #333;
		font-weight: bold;
		margin-left: 10rpx;
	}
}

.total-detail {
	width: 100%;
	background-color: #ffffff;
	border-top-left-radius: 20rpx;
	border-top-right-radius: 20rpx;
}

.detail-header {
	height: 88rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 30rpx;
	border-bottom: 1rpx solid #eee;
	position: relative;
	
	.title {
		font-size: 32rpx;
		color: #333;
	}
	
	.close-btn {
		position: absolute;
		right: 30rpx;
		top: 50%;
		transform: translateY(-50%);
		width: 44rpx;
		height: 44rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		font-size: 40rpx;
		color: #999;
		font-weight: 100;
	}
}

.detail-content {
	padding: 20rpx 30rpx;
	max-height: 60vh;
	overflow-y: auto;
	display: flex;
	flex-wrap: wrap;
}

.detail-item {
	display: flex;
	// justify-content: space-between;
	align-items: center;
	padding: 20rpx 0;
	border-bottom: 1rpx solid #f5f5f5;
	width: 340rpx;
	
	&:last-child {
		border-bottom: none;
	}
	
	.label {
		color: #666;
		font-size: 28rpx;
	}
	
	.value {
		color: #333;
		font-size: 28rpx;
	}
}

.list {
	.list-item {
		position: relative;
		view {
			display: flex;
			justify-content: space-between;
			
			text {
				flex: 1;
				text-align: left;
			}
		}
		&::after {
			content: '';
			position: absolute;
			left: 30rpx;
			right: 30rpx;
			bottom: 0;
			height: 1rpx;
			background-color: #D7DEEB;
		}
		&:last-child::after {
			display: none;
		}
	}
}

.time-filter {
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
	position: fixed;
    width: 100%;
    z-index: 999;
	display: flex;
	justify-content: space-between;
	align-items: center;
	
	.filter-item {
		display: flex;
		align-items: center;
		height: 70rpx;
		padding: 0 20rpx;
		
		.filter-text {
			margin-right: 10rpx;
			font-size: 28rpx;
			color: #333;
		}
	}
	
	.payment-btn {
		background-color: #2979ff;
		color: #fff;
		padding: 10rpx 30rpx;
		border-radius: 30rpx;
		font-size: 28rpx;
	}
}

.time-popup {
	background-color: #fff;
	
	.popup-header {
		height: 100rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		border-bottom: 1rpx solid #eee;
		
		.title {
			font-size: 32rpx;
			color: #333;
		}
	}
	
	.popup-content {
		.time-option {
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border-bottom: 1rpx solid #eee;
			
			.option-text {
				font-size: 30rpx;
				color: #333;
			}
			
			&:active {
				background-color: #f5f5f5;
			}
		}
	}
}

.date-picker-popup {
	background-color: #fff;
	
	.date-header {
		height: 90rpx;
		line-height: 90rpx;
		text-align: center;
		font-size: 32rpx;
		color: #333;
		border-bottom: 1px solid #eee;
	}
	
	.date-display {
		height: 80rpx;
		line-height: 80rpx;
		text-align: center;
		font-size: 28rpx;
		color: #2979ff;
		border-bottom: 1px solid #eee;
	}
	
	.date-tabs {
		display: flex;
		height: 80rpx;
		background: #fff;
		border-bottom: 1px solid #eee;
		
		.tab-item {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 28rpx;
			color: #666;
			position: relative;
			
			&.active {
				color: #2979ff;
				
				&::after {
					content: '';
					position: absolute;
					left: 0;
					bottom: 0;
					width: 100%;
					height: 2px;
					background-color: #2979ff;
				}
			}
		}
	}
	
	.picker-labels {
		height: 80rpx;
		display: flex;
		justify-content: space-around;
		align-items: center;
		background-color: #f8f8f8;
		border-bottom: 1px solid #eee;
		
		.label-item {
			flex: 1;
			text-align: center;
			font-size: 28rpx;
			color: #666;
		}
	}
	
	.picker-container {
		height: 400rpx;
		position: relative;
		
		.picker-view {
			width: 100%;
			height: 100%;
		}
		
		.picker-item {
			height: 80rpx;
			line-height: 80rpx;
			text-align: center;
			font-size: 32rpx;
			color: #333;
		}
	}
	
	.picker-actions {
		display: flex;
		height: 100rpx;
		border-top: 1px solid #eee;
		
		.picker-btn {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 32rpx;
			
			&.cancel {
				color: #333;
				background-color: #fff;
				border-right: 1px solid #eee;
			}
			
			&.confirm {
				color: #fff;
				background-color: #2979ff;
			}
		}
	}
}

.label-row {
	display: flex;
	justify-content: space-between;
	margin-bottom: 8rpx;
	
	.label-text {
		flex: 1;
		font-size: 24rpx;
		color: #666;
		&:first-child {
			margin-right: 20rpx;
		}
	}
}

.red-text {
    color: #ff0000;
	font-size: 28rpx;
}
.blue-text {
    color: #0000ff;
	font-size: 28rpx;
}
.purple-text {
    color: #800080;
	font-size: 28rpx;
}

.chart-header-bar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 20rpx;
	background-color: #fff;
	border-bottom: 1px solid #eee;
}

.chart-header-title {
	font-size: 32rpx;
	color: #333;
	font-weight: bold;
}

.chart-header-sort {
	padding: 10rpx 30rpx;
	background-color: #fff;
	border: 1px solid #eee;
	border-radius: 10rpx;
}

.title-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
}

.office-name {
    // flex: 1;
}

.status-normal {
    font-size: 24rpx;
}
/deep/ .list .u-cell-item-box .u-cell_title{
	display: flex;
	flex-direction: column;
}
</style>
